package ru.bragnikita.utils.swing.widget.dialog;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

/**
 * @author Nikita.Brazhnikov
 */
public abstract class ValueDialog<T> {

    private JDialog dialog;
    private Component dialogComponent;
    private T model;
    private boolean cancelled = false;

    public ValueDialog(Window parent, String title, T modelParameter) {
        dialog = new JDialog(parent, Dialog.ModalityType.APPLICATION_MODAL);
        model = modelParameter;
        JPanel rootComponent = new JPanel(new BorderLayout());
        this.dialogComponent = createPanel(rootComponent, modelParameter);

        dialog.getContentPane().setLayout(new BorderLayout());
        dialog.getContentPane().add(dialogComponent, BorderLayout.CENTER);

        JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonsPanel.add(new JButton(new AbstractAction() {
            {
                putValue(AbstractAction.NAME, "OK");
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                if (checkData()) {
                    model = collectData(model);
                    dialog.setVisible(false);
                }
            }
        }));
        buttonsPanel.add(new JButton(new AbstractAction() {
            {
                putValue(AbstractAction.NAME, "Cancel");
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                cancelled = true;
                dialog.setVisible(false);
            }
        }));
        dialog.getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
        dialog.setTitle(title);
        dialog.pack();
    }

    public T request() {
        cancelled = false;
        dialog.setVisible(true);
        if (cancelled)
            return null;
        else
            return model;
    }

    protected boolean checkData() {
        return true;
    }

    public T getModel() {
        return model;
    }

    protected abstract T collectData(T model);

    protected abstract Component createPanel(JPanel panel, T model);

}
